const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const ShareStatistics = sequelize.define('ShareStatistics', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      },
      comment: '分享用户ID'
    },
    invite_code: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: '邀请码'
    },
    share_channel: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: '分享渠道: wechat, moments, qq, qzone, weibo, copy, qrcode'
    },
    share_platform: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: '分享平台: miniprogram, h5, app'
    },
    click_count: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '点击次数'
    },
    register_count: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '注册转化次数'
    },
    ip_address: {
      type: DataTypes.STRING(45),
      allowNull: true,
      comment: 'IP地址'
    },
    user_agent: {
      type: DataTypes.TEXT,
      allowNull: true,
      comment: '用户代理'
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    }
  }, {
    tableName: 'share_statistics',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      {
        fields: ['user_id']
      },
      {
        fields: ['invite_code']
      },
      {
        fields: ['share_channel']
      },
      {
        fields: ['created_at']
      }
    ]
  });

  // 定义关联关系
  ShareStatistics.associate = (models) => {
    ShareStatistics.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user'
    });
  };

  return ShareStatistics;
};